package com.mab.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mab.mall.auth.feign.MemberFeignService;
import com.mab.mall.auth.vo.SocialUser;
import com.msb.common.constant.AuthConstant;
import com.msb.common.utils.HttpUtil;
import com.msb.common.utils.R;
import com.msb.common.vo.MemberVO;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;
    @RequestMapping("/oauth/weibo/success")
    public String weiboOAuth(@RequestParam("code")String code, HttpSession session,
                             HttpServletResponse servletResponse) throws Exception {
        Map<String,String> body = new HashMap<>();
        body.put("client_id","");
        body.put("client_secret","");
        body.put("grant_type","authorization_code");
        body.put("redirect_uri","http://localhost:10010/oauth/weibo/success");
        body.put("code",code);
        //根据code获取token
        ///oauth2/access_token?
        // client_id=YOUR_CLIENT_ID
        // &client_secret=YOUR_CLIENT_SECRET
        // &grant_type=authorization_code
        // &redirect_uri=YOUR_REGISTERED_REDIRECT_URI
        // &code=CODE
        HttpResponse response = HttpUtil.doPost("https://api.weibo.com",
                "/oauth2/access_token",
                "post",
                new HashMap<>(),
                null,
                body
        );
        int statusCode = response.getStatusLine().getStatusCode();
        if(statusCode !=200 ){
            //说明获取token失败
            return "redirect:http://localhost:10010/login.html";
        }
        //获取token成功
        String entity = EntityUtils.toString(response.getEntity()) ;
        SocialUser socialUser = JSONObject.parseObject(entity, SocialUser.class);
        R r = memberFeignService.oauth2Login(socialUser);
        if(r.getCode() != 0){
           //登录错误
            return "redirect:http://localhost:10010/login.html";
        }
        String entityJson = (String) r.get("entity");
        System.out.println("entityJson = " + entityJson);
        MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);
        session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
//        Cookie cookie = new Cookie("","");
//        servletResponse.addCookie(cookie);
        //注册成功跳转到商城首页
        return "redirect:http://localhost:8040/home";
    }

    }
